package com.lch.designpattern.template.jdbc;

import com.lch.designpattern.template.RowMapper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

/**
 * @author: liuchenhui
 * @create: 2019-06-23 16:50
 **/
public class JdbcTemplate {

    private DataSource dataSource;

    public JdbcTemplate(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    protected List<?> quertList(String sql, RowMapper<?> rowMapper, Object[] objects) {
        try {
            Connection connection = dataSource.getConnection();

            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            ResultSet set = this.exeuteQuery(preparedStatement, objects);

            List<?> list = this.parseResutl(set, rowMapper);

            set.close();

            preparedStatement.close();

            connection.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    private List<?> parseResutl(ResultSet set, RowMapper<?> rowMapper) throws SQLException {
        List<Object> list = new ArrayList<>();
        int sumNum = 0;
        while (set.next()) {
            list.add(rowMapper.mapRow(set, sumNum++));
        }
        return list;
    }

    private ResultSet exeuteQuery(PreparedStatement preparedStatement, Object[] objects) throws SQLException {
        for (int i = 0; i < objects.length; i++) {
            preparedStatement.setObject(i, objects[i]);
        }

        return preparedStatement.executeQuery();
    }
}
